package com.ikcai.service;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.codehaus.jackson.map.util.JSONPObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 打印服务类
 * Created by zhaoli on 2016/12/24.
 */
public class PrintService {
    private JSONPObject json;
    public PrintService(JSONPObject json)
    {
        this.json= json;
    }
    public byte[] print()
    {
       byte[] fileBytes = drawImage();
       fileBytes = toPdf(fileBytes);
       return fileBytes;
    }
    protected byte[] drawImage()
    {
        return null;
    }
    private byte[] toPdf(byte[] bytes)
    {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            BufferedImage img = ImageIO.read(in);
            Document doc = new Document(null, 0, 0, 0, 0);
            doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
            try {
                Image image = Image.getInstance(bytes);
                ByteArrayOutputStream ops= new ByteArrayOutputStream();
                PdfWriter.getInstance(doc, ops);
                doc.open();
                doc.add(image);
                doc.close();
                return ops.toByteArray();
            }catch (BadElementException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }


}
